package com.yonder.test.shutdown;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class ChatClient {

	private static String HOST = "127.0.0.1";
	private static int PORT = 8888;

	public void connect() throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
             .channel(NioSocketChannel.class)
             .handler(new ClientInitializer());
			Channel ch = b.connect(HOST, PORT).sync().channel();
			while (true) {
				Thread.sleep(1000);
			}
		} finally {
			group.shutdownGracefully();
		}
	}

	public static void main(String[] args) throws Exception {
		new ChatClient().connect();
	}
	
	public class ClientHandler extends SimpleChannelInboundHandler<String> {

	    @Override
	    public void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
	    	System.out.println("msg:" + msg);
	    }

	}
	
	public class ClientInitializer extends ChannelInitializer<SocketChannel> {


	    @Override
	    public void initChannel(SocketChannel ch) throws Exception {
	        ChannelPipeline pipeline = ch.pipeline();
	        //text line codec.
	        pipeline.addLast(new StringDecoder());
	        pipeline.addLast(new StringEncoder());

	        // and then business logic.
	        pipeline.addLast(new ClientHandler());
	    }
	}

}
